const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 网络请求工具函数
const request = (options) => {
  return new Promise((resolve, reject) => {
    console.log('发起网络请求:', {
      url: options.url,
      method: options.method,
      data: options.data
    });
    
    wx.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'X-Request-Source': 'weapp',
        ...options.header
      },
      success: (res) => {
        console.log('网络请求成功:', {
          statusCode: res.statusCode,
          data: res.data
        });
        
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          console.error('HTTP状态码错误:', res.statusCode);
          reject(new Error(`HTTP错误: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', {
          errMsg: err.errMsg,
          errno: err.errno
        });
        reject(err)
      }
    })
  })
}

// 获取API基础URL
const getApiBaseUrl = () => {
  const app = getApp()
  return app.globalData.apiBaseUrl || 'http://localhost:8088'
}

// 课程相关API
const courseAPI = {
  // 搜索课程
  searchCourse: (params) => {
    return request({
      url: `${getApiBaseUrl()}/api/course/search`,
      method: 'GET',
      data: params
    })
  },
  
  // 测试API连接
  testConnection: () => {
    return request({
      url: `${getApiBaseUrl()}/api/course/search`,
      method: 'GET',
      data: { currentUserId: 1 }
    })
  }
}

// 新闻/动态相关API
const newsAPI = {
  // 搜索新闻
  searchNews: (params) => {
    return request({
      url: `${getApiBaseUrl()}/api/news/search`,
      method: 'GET',
      data: params
    })
  }
}

// 会议相关API
const meetingAPI = {
  // 获取会议列表
  getMeetingList: (params) => {
    return request({
      url: `${getApiBaseUrl()}/api/meetings/list`,
      method: 'GET',
      data: params
    })
  }
}

module.exports = {
  formatTime,
  request,
  courseAPI,
  newsAPI,
  meetingAPI,
  getApiBaseUrl
}
